package com.ipkiss.incomespringboot.config;

import com.ipkiss.incomespringboot.common.Constants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


/**
 * @author WuYongheng
 * @date 2024/5/11
 * @describe 配置跨域资源共享
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许接收的域，写前端的地址
        config.addAllowedOrigin("http://localhost:8008");
        //发送cookies信息
        config.setAllowCredentials(true);
        //允许访问的方法
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        //允许的头信息
        config.addAllowedHeader("*");
        //跨域请求最大有效时长
        config.setMaxAge(Constants.ONE_DAY);
        //添加路径映射，拦截一切请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        //返回新的CorsFilter
        return new CorsFilter(configSource);
    }
}
